const WebSocket = require('ws');
const {port} = require('../../config.json').server
const { stdout } = require('single-line-log')
const {openEditer} = require('../utils/shell')


async function useWS(originLog,serverOnCallbcak,){
    const server = new WebSocket.Server({ port },function(){
        originLog('🔵 node-conosle => websocket服务开启:',`ws://localhost:${port}`)
    });


    // 连接成功后添加事件
    const connectHandler = (ws) => {
        originLog('🔵 node-conosle => 客户端已连接')
        ws.connected = true
        typeof serverOnCallbcak == 'function' && serverOnCallbcak(ws)
        // 监听客户端出错
        ws.on('error', errorHandler)
        // 监听客户端断开链接
        ws.on('close', closeHandler)
        // 监听客户端发来的消息
        ws.on('message', messageHandler)
    }

    // 监听接收客户端信息回调
    // 注意：因为这里用到this的指向，因此用普通的函数
    function messageHandler(data) {
        let res 
        try{
            res = JSON.parse(data)
        }catch{
            res = { ModeCode :'fail',data}
        }
        const { ModeCode } = res
        // stdout(`接收客户端${ModeCode}消息`)
        switch (ModeCode) {
            case 'hello':
                // originLog(`收到hello消息:${res.message}`)
                // 需要发送信息给客户端以此说明连接成功
                this.send(JSON.stringify({ ModeCode :'hello',message:'hello'}))
                break;
            case 'message':
                // originLog('收到消息')
                break;
            case 'openEditer':
                // originLog('打开VScode',res.path)
                openEditer(res.path,originLog)
                break
            case 'fail':
                originLog(`🔵 node-conosle => 信息解析失败:${data}`)
                break;
            case 'heart_beat':
                stdout(`🔵 node-conosle => 接收客户端${ModeCode}消息:heart_beatCount=${res.times}`)

                // 需要发送信息给客户端以此说明连接成功
                this.send(JSON.stringify(res))
                break;
            default:
                break
        }
    }

    // 监听客户端出错回调
    const errorHandler = (error) => {
        originLog('🔵 node-conosle => errorHandler===>客户端出错', error)
    }

    // 监听客户端断开连接回调
    const closeHandler = (e) => {
        originLog('🔵 node-conosle => closeHandler===>客户端断开🔗', e)
    }

    // 建立连接
    server.on('connection', connectHandler)

  
}

module.exports = useWS